const Mock = require('mockjs')

const goodsList = []
const count = 50

for (let i = 0; i < count; i++) {
  goodsList.push(Mock.mock({
    id: Mock.Random.increment(),
    name: Mock.Random.ctitle(3, 8),
    category: Mock.Random.pick(['drink', 'snack', 'daily', 'other']),
    price: Mock.Random.float(1, 50, 0, 2),
    image: Mock.Random.image('100x100', Mock.Random.color(), Mock.Random.cword(2, 3)),
    description: Mock.Random.cparagraph(1, 3),
    stock: Mock.Random.integer(0, 100),
    status: Mock.Random.pick([0, 1]),
    createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  }))
}

module.exports = [
  // 获取商品列表
  {
    url: '/api/goods/list',
    type: 'get',
    response: config => {
      const { name, category, pageNum = 1, pageSize = 10 } = config.query
      console.log(config.query)

      let filteredList = [...goodsList].filter(item => {
        if (name && item.name.indexOf(name) < 0) return false
        if (category && item.category !== category) return false
        return true
      })

      const pageList = filteredList.slice((pageNum - 1) * pageSize, pageNum * pageSize)

      return {
        code: 200,
        message: 'success',
        data: {
          list: pageList,
          total: filteredList.length
        }
      }
    }
  },

  // 添加商品
  {
    url: '/api/goods/add',
    type: 'post',
    response: config => {
      const newGoods = config.body
      newGoods.id = Mock.Random.increment()
      newGoods.createTime = Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
      goodsList.unshift(newGoods)
      return {
        code: 200,
        message: '添加成功',
        data: newGoods
      }
    }
  },

  // 更新商品
  {
    url: '/api/goods/update',
    type: 'post',
    response: config => {
      const updatedGoods = config.body
      const index = goodsList.findIndex(item => item.id === updatedGoods.id)
      if (index !== -1) {
        goodsList.splice(index, 1, updatedGoods)
        return {
          code: 200,
          message: '修改成功',
          data: updatedGoods
        }
      } else {
        return {
          code: 404,
          message: '商品不存在'
        }
      }
    }
  },

  // 删除商品
  {
    url: '/api/goods/delete',
    type: 'post',
    response: config => {
      const { id } = config.body
      const index = goodsList.findIndex(item => item.id === id)
      if (index !== -1) {
        goodsList.splice(index, 1)
        return {
          code: 200,
          message: '删除成功'
        }
      } else {
        return {
          code: 404,
          message: '商品不存在'
        }
      }
    }
  }
]